<?php

//$email = get_input('email');
//$username = get_input('username');
//$password = get_input('password');
//$firstname = get_input('first_name');
//$lastname = get_input('last_name');
//$avatar_url = get_input('avatar_url');
$gc_id = get_input('gamecenter_id');
$alias = get_input('gamecenter_alias');

$timestamp = get_input('timestamp');

$client_id = get_input('client_id');

$signature = get_input('signature');

/*
 * NSString * sourceString = [NSString stringWithFormat:@"%@,%@,%@,%@,%@,%@,%f",
                                   fbEmail,
                                   fbUsername,
                                   fbFirstName,
                                   fbLastName,
                                   fbAvatarUrl,
                                   fbUid,
                                   currentTimeStamp];
 */

$base_string =
    sprintf(
            "%s,%s,%f",
            $gc_id,
            $alias,
            $timestamp

    );

$hmac = compute_hash($base_string, REGISTER);
//die('base = ' . $base_string . ', sig = ' . $signature . ', hmac = ' . $hmac);
// For test
 $hmac = $signature;

if ($hmac != $signature) {
    $result = export_result(400, 'Cannot verify request');
} else {
    $result = export_result(200, '');
    $gamecenterAccounts = greengar_get_gamecenter($gc_id, ELGG_ENTITIES_ANY_VALUE);
    if ($gamecenterAccounts && $gamecenterAccounts[0]) {
        $gamecenterAccount = $gamecenterAccounts[0];
        $userid = $gamecenterAccount->owner_guid;
        $userEntity = get_user($userid);
        if ($userEntity) {
            login($userEntity);
            $oauth = oauth2_get_server();
            $result['result'] = $oauth->directlyGrantToken($client_id);
        }
    } else {
        // $result = export_result(200, 'Facebook id ' . $fb_id . ' associate with no Greengar Account');
        // Register a new account for this
//
//        die();
//        echo ' try email ';
        //$userEntity = get_user_by_email($email);
        //if ($userEntity && is_array($userEntity)) {
//            echo 'yeah ';

        //    $userEntity = array_shift($userEntity);
        //    login($userEntity);
        //    $oauth = oauth2_get_server();
        //    $result['result'] = $oauth->directlyGrantToken($client_id);
        //} else {
//            echo ' new user '
//            include(dirname(__FILE__) . '/register.php');
            $result = export_result(400, "This gamecenter id $gc_id+$alias doesn\'t associate with any user");
        
            // Create new account
//        }
    }
}
//echo '123';
echo json_encode($result);
?>